import React, { useReducer } from 'react'


export default function ReducerDeom() {
  // 定义初始化值
  const initPerson = {
    name: '夏天',
    age: 27,
    gender: '男'
  }

  // 定义reduce方法
  const reducer = (state, action) => {
    const { type, payload } = action
    switch (type) {
      case 'addAge':
        return { ...state, age: state.age + 1 }
      case 'subAge':
        return { ...state, age: state.age - 1 }
      case 'changePerson':
        return { ...payload }
      default:
        return state
    }
  }

  const [state, dispatch] = useReducer(reducer, initPerson)

  return (
    <>
      <h3>useReducer的使用</h3>
      <ul>
        <li>{state.name}</li>
        <li>{state.age}</li>
        <li>{state.gender}</li>
      </ul>
      <button onClick={() => dispatch({ type: 'changePerson', payload: { name: '周一帆', age: 18, gender: '女' } })}>换人</button>
      <button onClick={() => dispatch({ type: 'addAge' })}>添加年龄</button>
      <button onClick={() => dispatch({ type: 'subAge' })}>减小年龄</button>
    </>
  )
}